<!--
 * @Author: DavidOba 1196393631@qq.com
 * @Date: 2024-12-17 14:08:31
 * @LastEditors: DavidOba 1196393631@qq.com
 * @LastEditTime: 2025-04-24 14:14:48
 * @FilePath: \daoming-official-website\ruoyi-ui\src\views\official\news\newActivity.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        {{ productName+'('+detailOne+')' }}
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="operationList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="类型" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.introduce_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="文字说明"
        align="center"
        prop="operationLocation"
      /> -->
      <el-table-column label="文字说明/图片列表" align="left">
        <template slot-scope="scope">
            <div  class="preserve-line-breaks" v-html="scope.row.intro"  v-if="scope.row.type===0"></div>
            <el-image :src="apiUrl + scope.row.pictureUrl" v-if="scope.row.type===1" :preview-src-list="[apiUrl + scope.row.pictureUrl]"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="显示排序" align="center" prop="orderNum" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改公司近期详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="420px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="类型" style="width: 280px;" @change="handleChangeType">
            <el-option
              v-for="dict in dict.type.introduce_type"
              :key="dict.value"
              :label="dict.label"
              :value="Number(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文字说明" prop="intro" v-if="form.type===0">
          <el-input
            type="textarea"
            v-model="form.intro"
            placeholder="请输入文字说明"
            autosize
          ></el-input>
        </el-form-item>
        <el-form-item label="图片列表" prop="fileList" v-else>
          <div class="avatar-list">
            <div class="avatar" v-if="form.fileList.length>0">
              <img :src="getImageUrl(form.fileList[0])" class="avatar"/>
              <i class="el-icon-error avatar-close" @click="handleRemove(0)"></i>
            </div>

            <el-upload
              class="avatar-uploader"
              ref="upload"
              :show-file-list="false"
              action="/index/upload"
              :before-upload="beforeUpload"
              :on-change="handleChange"
              :auto-upload="false"
              :data="form"
              accept="image/png,image/gif,image/jpg,image/jpeg"
              v-if="form.fileList.length===0"
            >
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="显示排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" controls-position="right" :min="0" style="width: 280px;"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getItemList,
  addLtdProductDetailItem,
  updateDetailItem,
  deleteLtdProductDetailItem
} from "@/api/official/bookList";

export default {
  name: "bookSet",
  dicts: ['introduce_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      apiUrl: process.env.VUE_APP_FILE_URL,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      // 公司近期详情表格数据
      operationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 10,
        pageSize: 10,
        createName: null,
        createId: null,
        operationDate: null,
        operationTitle: null,
        operationLocation: null,
        status: null,
        isAsc: "asc",
        orderByColumn: "orderNum",
      },
      // 表单参数
      form: {
        productId:'',
        detailId:'',
        type:0,
        intro:'',
        fileList:[],
        orderNum:'',
        id:'',
      },
      // 表单校验
      rules: {
        operationTitle: [
          { required: true, message: "活动名称不能为空", trigger: "blur" },
        ],
        operationLocation: [
          { required: true, message: "举办地点不能为空", trigger: "blur" },
        ],
        operationDate: [
          { required: true, message: "举办日期不能为空", trigger: "blur" },
        ],
      },
      detailId:'',
      detailOne:'',
      productName:'',
      productId:''
    };
  },
  computed: {
		// 计算两个周期值
		getImageUrl: function () {
			return (file)=>{
        return URL.createObjectURL(file);
      }
		}
	},
  created() {
    const {detailId,productId,detailOne,productName} = this.$route.query;
    this.form.detailId = detailId;
    this.form.productId = productId;
    this.detailOne = detailOne;
    this.productName = productName;
    this.getList();
  },
  methods: {
    /** 查询公司近期详情列表 */
    getList() {
      this.loading = true;
      getItemList(this.form.detailId).then((response) => {
        this.operationList = response.data;
        this.loading = false;
      });
    },
    handleChangeType(e){
      if(e==='0'){
        this.form.fileList = [];
      }
    },
    handleRemove(index){
      this.form.fileList.splice(index,1);
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === 0 ? "启用" : "停用";
      this.$modal
        .confirm("确认" + text + "？")
        .then(function () {
          return updateOperation(row);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === 0 ? 1 : 0;
        });
    },
    async toFile(source, fileName, mimeType) {
      let blob;
      try {
        if (typeof source === 'string') {
          // 如果 source 是 URL，通过 fetch 获取 Blob
          const response = await fetch(source);
          blob = await response.blob();
        }

        // 如果未提供 mimeType，尝试从 Blob 或 URL 推断
        if (!mimeType) {
          mimeType = blob.type || 'application/octet-stream';
        }

        // 将 Blob 转换为 File 对象
        const file = new File([blob], fileName, { type: mimeType });
        return file;
      } catch (error) {
        this.$modal.magError('操作失败')
      }

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        detailId : this.form.detailId,
        productId : this.form.productId,
        type:0,
        intro:'',
        fileList:[],
        orderNum:'',
        id:''
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      // this.reset();
      this.open = true;
      this.title = "添加详情";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      let _this = this;
      this.form = {...row,fileList:[]};
      try {
        if(this.form.type === 1 && this.form.pictureUrl){
          this.toFile((this.apiUrl+this.form.pictureUrl),'1.png','image/png').then(res=>{
            if(res){
              _this.form = {
                ..._this.form,
                fileList:[res]
              }
              console.log('_this.form',_this.form);
            }
          })

        }
        this.open = true;
        this.title = "修改详情";
      } catch (error) {
        this.$modal.msgError("操作失败");
      }

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let formData = new FormData();
          for (const key in this.form) {
            if (this.form.hasOwnProperty(key) && key!=='fileList' && key!=='createId') {
              // 将每个属性及其值添加到 FormData 中
              formData.append(key, this.form[key]);
            }
          }
          if(this.form.type===1){
            this.form.fileList.map(item=>{
              formData.append('fileList',item);
              console.log('item',item);
            })
          }
          if (this.form.id) {
            updateDetailItem(formData).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.reset();
            });
          } else {
            addLtdProductDetailItem(formData).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.reset();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除该数据项？')
        .then(function () {
          return deleteLtdProductDetailItem(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/operation/export",
        {
          ...this.queryParams,
        },
        `operation_${new Date().getTime()}.xlsx`
      );
    },
    handleChange(file, fileList) {
      // const formData = new FormData();
      // formData.append('file', file.raw)
      // uploadPic(formData).then(res=>{
      //   if(res && res.url){
      //     this.$modal.msgSuccess("上传成功");
      //     this.form.picUrl = res.url;
      //   }
      // })
      this.form.fileList.push(file.raw);
    },

    beforeUpload(file) {
      return true;
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-textarea{
  .el-textarea__inner{
    min-height: 100px !important;
  }
}
.preserve-line-breaks {
  white-space: pre-line; /* 保留换行符 */
  text-align: left;
}
.avatar-uploader {
  ::v-deep .el-upload {
    border: 1px dashed #d9d9d9 !important;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 88px;
  height: 88px;
  line-height: 88px;
  text-align: center;
}

.avatar-list{
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  row-gap: 10px;
}

.avatar {
  width: 88px;
  height: 88px;
  display: block;
  border-radius: 6px;
  position: relative;
  z-index: 1;

  .avatar-close{
    position: absolute;
    right: -8px;
    top: -8px;
    font-size: 20px;
    color: red;
    z-index: 10;
    cursor: pointer;
    background: #ffffff;
    border-radius: 10px;
  }
}
</style>
